package com.gy.componit;

import com.gy.event.SimpleBulletDisappearEvent;
import com.gy.game.Game;
import com.gy.utils.CrashUtil;
import lombok.Getter;
import lombok.Setter;

import java.awt.*;
import java.util.*;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;

/**
 * 普通子弹
 * @author Dsy
 * @create 2022-02-04  2:22
 */
@Getter
@Setter
public class SimpleBullet extends Bullet{

    private double size = 2.5d;
    private Color color = Color.black;
    private BigDecimal v = new BigDecimal(1);
    // 特效是否开启
    private boolean specialEffect = true;
    private LinkedList<SimpleBulletSpecialEffect> effectList = null;

    @Override
    public void paint(Graphics g) {
        g.setColor(color);
        g.fillOval((int)(x.doubleValue()-size), (int)(y.doubleValue()-size), (int)(size*2), (int)(size*2));
        // 画特效
        if(specialEffect) {
            if(effectList != null) {
                synchronized (effectList) {
                    effectList.forEach(e -> e.paint(g));
                }
            }
        }
    }

    @Override
    public void move(Game game) {
        x = x.add(vx.multiply(v));
        y = y.add(vy.multiply(v));
        // 检查地块碰撞
        Collection<Plot> plots = game.getWarMap().getPlot(x.doubleValue(), y.doubleValue(), size);
        if(plots.size() > 0) {
            for(Plot plot: plots) {
                if(plot.getTeam() != team) {
                    plot.setTeam(team);
                    disappear(game);
                    return;
                }
            }
        }
        // 检查边界
        boolean b = CrashUtil.ballWarMap(x.doubleValue(), y.doubleValue(), size, game.getWarMap());
        if(b) {
            disappear(game);
            return;
        }
        // 添加和删除特效
        if(specialEffect) {
            if(effectList == null) {
                effectList = new LinkedList<>();
            }
            synchronized (effectList) {
                SimpleBulletSpecialEffect effect = new SimpleBulletSpecialEffect();
                effect.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), 150).darker().darker());
                effect.setX(x);
                effect.setY(y);
                effect.setSize(size);
                effectList.add(effect);
                SimpleBulletSpecialEffect peek = effectList.peek();
                while (peek.getLife() <= 0) {
                    effectList.remove(peek);
                    peek = effectList.peek();
                }
            }
            // 特效的move
            effectList.forEach(e -> e.move(game));
        }
    }

    // 子弹消失
    public void disappear(Game game) {
        game.addEvent(new SimpleBulletDisappearEvent(this));
    }
}
